/**
 * Created by lenovo on 2017/2/22.
 */
'use strict'
const path=require('path');
const fs=require('fs');
const xtpl=require('xtpl');
//获取服务器
const getMongo=require(path.join(__dirname,'../tools/getdb.js'))

exports.getInfo=(req,res)=>{
    //连接服务器
    //管理页面
   const keyword=req.query.keyword || '';
    getMongo.find('studeninfo',{name:{$regex:keyword}},(docs)=>{
        xtpl.renderFile(path.join(__dirname,'../views/studentlist.html'),{studentlist:docs,keyword:keyword,loginedname:req.session.username},(err,data)=> {
            res.setHeader("Content-Type","text/html;charset=utf-8")

            res.end(data);
        })
    })
}
//进入新增页面
exports.getAddPage=(req,res)=>{
    xtpl.renderFile(path.join(__dirname,'../views/add.html'),{loginedname:req.session.username},(err,data)=> {
        res.setHeader("Content-Type","text/html;charset=utf-8")
        res.end(data);
    })
}
//添加
exports.addStudent=(req,res)=>{
    const parms=req.body;
    getMongo.add('studeninfo',parms,(isSuccess)=>{
            if(isSuccess){
                res.end("<script>window.location.href='/student/info'</script>")
            }else{
                res.end("<script>alert('错误')</script>")
            }
        })
}
//进入修改页面
exports.getUpdatePage=(req,res)=>{
    const studentId = req.params.studentId;
   getMongo.findOne('studeninfo',{_id:getMongo.ObjectId(studentId)},(doc)=>{
        xtpl.renderFile(path.join(__dirname,'../views/edit.html'),{student:doc,loginedname:req.session.username},(err,data)=>{
            if(err){
                console.log(err);
            }
            res.end(data);
        })
   })
};

//修改数据
exports.updateMessange=(req,res)=>{
    const studentId = req.params.studentId;
    const parms=req.body;
    console.log(studentId);
    getMongo.updateOne('studeninfo',{_id:getMongo.ObjectId(studentId)},parms,(isSuccess)=>{
        if(isSuccess){
            res.end("<script>window.location.href='/student/info'</script>")
        }else {
            res.end("<script>alert('错误')</script>")
        }
    })
}
//删除数据
exports.deleteMessage=(req,res)=> {
    const studentId = req.params.studentId;
    getMongo.delete('studeninfo', {_id: getMongo.ObjectId(studentId)}, (isSuccess)=> {
        const result = {status:1,message:'删除成功'}
        if(!isSuccess){
            result.status=0;
            result.message='错误';
        }
        res.json(result);
    })
}
